package com.thread.sync.sync08;

import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class Provider implements Runnable {
    //共享缓存区
    private BlockingQueue<Data> queue;
    //多线程间是否启动变量，有强制从主内存中刷新的功能。即时返回线程的状态,需要使用volatile
    private volatile boolean isRunning = true;
    //id生成器
    private static AtomicInteger count = new AtomicInteger();

    //构造器
    public Provider(BlockingQueue<Data> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        while (isRunning) {
            try {
                //模拟生产数据耗时
                Thread.sleep(new Random().nextInt(1000));
                //id累加
                int id = count.incrementAndGet();
                //生产数据
                Data data = new Data(Integer.toString(id), "数据" + id);
                System.out.println("当前线程" + Thread.currentThread().getName() + "生产了数据" + id + ",并装载到缓冲队列中");
                //2秒内成功添加,返回true,否则返回false
                if (!this.queue.offer(data, 2, TimeUnit.SECONDS)) {
                    System.out.println("装载失败.....");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    //停止生产数据
    public void stop() {
        this.isRunning = false;
    }


}
